<template>
  <div class="app-container">
    

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="会话名称" prop="sessionName">
        <el-input
          v-model="queryParams.sessionName"
          placeholder="请输入会话名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会话日期" prop="sessionDate">
        <el-date-picker clearable
          v-model="queryParams.sessionDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择会话日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="会话状态" prop="sessionStatus">
        <el-select v-model="queryParams.sessionStatus" placeholder="请选择会话状态" clearable>
          <el-option
            v-for="dict in session_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <div class="toolbar-wrapper">
        <div class="left-section">
          <el-checkbox 
            v-model="isAllSelected"
            @change="handleSelectAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
          <span class="selected-count" v-if="selectedSessions.length > 0">
            已选择 {{ selectedSessions.length }} 项
          </span>
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="selectedSessions.length === 0"
            @click="handleBatchDelete"
            v-hasPermi="['system:sessions:remove']"
          >批量删除</el-button>
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:sessions:export']"
          >导出</el-button>
        </div>

        <div class="right-section">
          
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>
    </el-row>

    <el-row :gutter="16" v-loading="loading">
      <el-col :xs="24" :sm="12" :md="8" :lg="7.5" v-for="item in sessionsList" :key="item.id">
        <el-card 
          class="session-card" 
          shadow="hover"
          :class="{ 'is-selected': selectedSessions.includes(item.id) }"
        >
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-checkbox 
                  v-model="item.isSelected"
                  @change="(val) => handleSelectSession(val, item.id)"
                />
                <div class="session-title">
                  <div class="title-content">
                    <el-icon><ChatDotRound /></el-icon>
                    <span>{{ item.sessionName || '未命名会话' }}</span>
                  </div>
                  <el-button
                    type="danger"
                    link
                    class="edit-name-btn"
                    @click.stop="handleEditName(item)"
                  >
                    <el-icon><Edit /></el-icon>
                    <span class="hover-text">修改会话名称</span>
                  </el-button>
                </div>
              </div>
              <el-tag :type="item.sessionStatus === '0' ? 'success' : 'info'" size="small">
                {{ item.sessionStatus === '0' ? '正常' : '已结束' }}
              </el-tag>
            </div>
          </template>
          
          <div class="card-content">
            <div class="info-item">
              <el-icon><Calendar /></el-icon>
              <span>{{ parseTime(item.sessionDate, '{y}-{m}-{d}') }}</span>
            </div>
            
            <div class="card-actions">
              <el-button 
                type="primary" 
                link 
                @click="handleViewDialogs(item)"
                v-hasPermi="['system:sessions:edit']"
              >
                <el-icon><View /></el-icon>
                查看对话
              </el-button>
              <el-button 
                type="danger" 
                link 
                @click="handleDelete(item)"
                v-hasPermi="['system:sessions:remove']"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-empty
      v-if="!loading && (!sessionsList || sessionsList.length === 0)"
      description="暂无会话记录"
    >
      <template #extra>
        <el-button type="primary" @click="handleQuery">刷新</el-button>
      </template>
    </el-empty>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog 
      v-model="dialogVisible" 
      :title="currentSession.sessionName || '未命名会话'" 
      width="60%" 
      class="dialog-wrapper"
      :close-on-click-modal="false"
    >
      <template #header>
        <div class="dialog-title">
          <div class="title-left">
            <span class="session-name">{{ currentSession.sessionName || '未命名会话' }}</span>
            <el-tag size="small" :type="currentSession.sessionStatus === '0' ? 'success' : 'info'">
              {{ currentSession.sessionStatus === '0' ? '进行中' : '已结束' }}
            </el-tag>
            <span class="session-date">{{ parseTime(currentSession.sessionDate) }}</span>
          </div>
        </div>
      </template>

      <div class="dialog-header">
        <div class="header-actions">
          <el-button type="primary" class="dialog-button" @click="toAIChat">
            <el-icon><ChatLineRound /></el-icon>
            继续对话
          </el-button>
          <el-button type="danger" class="dialog-button" @click="handleDeleteSessions">
            <el-icon><Delete /></el-icon>
            删除会话
          </el-button>
        </div>
      </div>
      
      <div class="dialog-container">
        <div v-if="!dialogList || dialogList.length === 0" class="empty-state">
          <el-empty 
            :image-size="120"
            description="暂无对话记录"
          >
            <template #extra>
              <el-button type="primary" @click="toAIChat">
                <el-icon><ChatLineRound /></el-icon>
                开始对话
              </el-button>
            </template>
          </el-empty>
        </div>

        <template v-else>
          <div v-for="(item, index) in dialogList" 
               :key="index" 
               class="dialog-item"
               :class="{ 'self-message': item.isUser }">
            <div class="avatar">
              <el-avatar :size="40" :src="item.isUser ? userAvatar : aiAvatar"/>
            </div>
            <div class="message-wrapper">
              <div class="user-name">{{ item.isUser ? '我' : 'AI助手' }}</div>
              <div class="dialog-content" :class="{ 'ai-message': !item.isUser }">
                {{ item.dialog }}
              </div>
              <div class="message-time">{{ parseTime(item.createTime) }}</div>
            </div>
          </div>
        </template>
      </div>
    </el-dialog>

    <el-dialog
      v-model="editNameDialogVisible"
      title="修改会话名称"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="editNameForm" ref="editNameFormRef">
        <el-form-item
          label="会话名称"
          prop="sessionName"
          :rules="[{ required: true, message: '请输入会话名称', trigger: 'blur' }]"
        >
          <el-input 
            v-model="editNameForm.sessionName"
            placeholder="请输入会话名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editNameDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditName">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sessions">
import { listSessions, getSessions, delSessions, addSessions, updateSessions, getDialogsBySessionId } from "@/api/system/sessions";
import { ChatDotRound, Calendar, View, Delete, Edit } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance();
const { session_status } = proxy.useDict('session_status');

const sessionsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dialogVisible = ref(false);
const dialogList = ref([]);
const currentSession = ref({});
const selectedSessions = ref([]);
const isAllSelected = ref(false);
const isIndeterminate = ref(false);
const editNameDialogVisible = ref(false);
const editNameForm = ref({
  id: '',
  sessionName: ''
});
const editNameFormRef = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    sessionName: null,
    sessionDate: null,
    sessionStatus: null
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    sessionName: [
      { required: true, message: "会话名称不能为空", trigger: "blur" }
    ],
    sessionDate: [
      { required: true, message: "会话日期不能为空", trigger: "blur" }
    ],
    sessionStatus: [
      { required: true, message: "会话状态不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询历史会话列表 */
function getList() {
  loading.value = true;
  listSessions(queryParams.value).then(response => {
    sessionsList.value = response.rows.map(item => ({
      ...item,
      isSelected: selectedSessions.value.includes(item.id)
    }));
    total.value = response.total;
    loading.value = false;
    
    // 更新全选状态
    const checkedCount = selectedSessions.value.length;
    const totalCount = sessionsList.value.length;
    isAllSelected.value = checkedCount === totalCount && totalCount > 0;
    isIndeterminate.value = checkedCount > 0 && checkedCount < totalCount;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    sessionName: null,
    sessionDate: null,
    sessionStatus: null
  };
  proxy.resetForm("sessionsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加历史会话";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSessions(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改历史会话";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["sessionsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSessions(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSessions(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 进入会话
function toAIChat(){
  // proxy.$router.push({ path: '/aiChat', query: { sessionId: row.id } });
  console.log("进入会话");
}
//对话框删除
function handleDeleteSessions() {
  const sessionId = currentSession.value.id;
  proxy.$modal.confirm('是否确认删除该会话？').then(function() {
    return delSessions(sessionId);
  }).then(() => {
    dialogVisible.value = false; // 关闭对话框
    getList(); // 刷新列表
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除历史会话编号为"' + _ids + '"的数据项？').then(function() {
    return delSessions(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/sessions/export', {
    ...queryParams.value
  }, `sessions_${new Date().getTime()}.xlsx`)
}


/** 查看对话记录按钮操作 */
function handleViewDialogs(row) {
  console.log("查看会话ID：", row.id);
  currentSession.value = row; // 保存当前会话信息
  getDialogsBySessionId(row.id).then(response => {
    dialogList.value = response.data;
    dialogVisible.value = true;
  });
}

// 处理会话选择
function handleSelectSession(checked, sessionId) {
  if (checked) {
    if (!selectedSessions.value.includes(sessionId)) {
      selectedSessions.value.push(sessionId);
    }
  } else {
    selectedSessions.value = selectedSessions.value.filter(id => id !== sessionId);
  }
  
  // 更新全选状态
  const checkedCount = selectedSessions.value.length;
  const totalCount = sessionsList.value.length;
  
  isAllSelected.value = checkedCount === totalCount && totalCount > 0;
  isIndeterminate.value = checkedCount > 0 && checkedCount < totalCount;
}

// 批量删除方法
function handleBatchDelete() {
  if (selectedSessions.value.length === 0) {
    proxy.$modal.msgError("请选择要删除的会话");
    return;
  }
  
  proxy.$modal.confirm('是否确认删除选中的' + selectedSessions.value.length + '个会话？').then(function() {
    return delSessions(selectedSessions.value.join(','));
  }).then(() => {
    getList();
    selectedSessions.value = []; // 清空选中数组
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 处理全选
function handleSelectAll(val) {
  sessionsList.value.forEach(item => {
    item.isSelected = val;
    handleSelectSession(val, item.id);
  });
  isIndeterminate.value = false;
}

// 处理修改名称
function handleEditName(row) {
  editNameForm.value.id = row.id;
  editNameForm.value.sessionName = row.sessionName;
  editNameDialogVisible.value = true;
}

// 提交修改名称
function submitEditName() {
  editNameFormRef.value.validate((valid) => {
    if (valid) {
      updateSessions({
        id: editNameForm.value.id,
        sessionName: editNameForm.value.sessionName
      }).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        editNameDialogVisible.value = false;
        getList(); // 刷新列表
      });
    }
  });
}

getList();
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.session-card {
  margin-bottom: 16px;
  transition: all 0.3s;
  border-radius: 16px;
  overflow: hidden;
  background-color: #f9f9f9;

  :deep(.el-card__header) {
    border-radius: 16px 16px 0 0;
    background-color: #f9f9f9;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  }

  :deep(.el-card__body) {
    border-radius: 0 0 16px 16px;
    background-color: #f9f9f9;
  }

  &:hover {
    transform: translateY(-2px);
    background-color: #f5f5f5;

    :deep(.el-card__header),
    :deep(.el-card__body) {
      background-color: #f5f5f5;
    }
  }

  .card-header {
    .session-title {
      .edit-name-btn {
        display: flex;
        align-items: center;
        gap: 4px;
        padding: 4px 8px;
        
        .el-icon {
          font-size: 16px;
        }

        .hover-text {
          display: none;
          font-size: 12px;
        }

        &:hover {
          background-color: rgba(#f56c6c, 0.1);
          
          .hover-text {
            display: inline-block;
          }
        }
      }
    }
  }

  .card-content {
    .info-item {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #606266;
      margin-bottom: 16px;

      .el-icon {
        font-size: 16px;
      }
    }

    .card-actions {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #EBEEF5;

      .el-button {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }

  // 添加选中状态样式
  &.is-selected {
    border: 2px solid #409EFF;
    
    .el-checkbox {
      :deep(.el-checkbox__input.is-checked) {
        .el-checkbox__inner {
          background-color: #409EFF;
          border-color: #409EFF;
        }
      }
    }
  }

  .card-header {
    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .el-checkbox {
        margin-right: 8px;
      }
    }
  }
}

// 空状态样式
.el-empty {
  padding: 40px 0;
}

.dialog-wrapper {
  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__header) {
    padding: 20px;
    margin-right: 0;
    border-bottom: 1px solid #e4e7ed;
  }

  .dialog-title {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .session-name {
        font-size: 18px;
        font-weight: 500;
        color: #303133;
      }

      .el-tag {
        margin: 0 8px;
      }

      .session-date {
        color: #909399;
        font-size: 13px;
      }
    }
  }

  .dialog-header {
    padding: 12px 20px;
    background: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;

    .header-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
    }
  }
}

.dialog-container {
  height: 65vh;
  overflow-y: auto;
  padding: 20px;
  background: #f7f7f7;
}

.dialog-item {
  margin-bottom: 25px;
  display: flex;
  gap: 12px;
}

.avatar {
  flex-shrink: 0;
}

.message-wrapper {
  max-width: 70%;
}

.user-name {
  font-size: 13px;
  color: #666;
  margin-bottom: 6px;
}

.dialog-content {
  background: #fff;
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.6;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.ai-message {
  background: #f0f9ff;
  border: 1px solid #e6f4ff;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 自己发送的消息样式 */
.self-message {
  flex-direction: row-reverse;
}

.self-message .message-wrapper {
  align-items: flex-end;
}

.self-message .dialog-content {
  background: #409EFF;
  color: #fff;
}

.self-message .user-name,
.self-message .message-time {
  text-align: right;
}

/* 滚动条样式 */
.dialog-container::-webkit-scrollbar {
  width: 6px;
}

.dialog-container::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
}

.dialog-container::-webkit-scrollbar-track {
  background: transparent;
}

.empty-state {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-state :deep(.el-empty__description) {
  font-size: 14px;
  color: #909399;
  margin-top: 20px;
}

.empty-state :deep(.el-empty__bottom) {
  margin-top: 20px;
}

.empty-state :deep(.el-button) {
  padding: 12px 24px;
  font-size: 14px;
}

.empty-state :deep(.el-icon) {
  margin-right: 6px;
  font-size: 16px;
}

.toolbar-wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  
  .left-section {
    display: flex;
    align-items: center;
    gap: 16px;

    .el-checkbox {
      margin: 0;
    }

    .selected-count {
      font-size: 14px;
      color: #606266;
      margin-right: 8px;
    }

    .el-button {
      margin-left: 0;
    }
  }

  .right-section {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.select-toolbar {
  display: none;
}
</style>
